<template>
  <div class="register-container">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <span>用户注册</span>
        </div>
      </template>

      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        size="large"
      >
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="3~16位字母/数字/下划线" />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            show-password
            placeholder="8~20位，含字母和数字"
          />
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="confirmPwd">
          <el-input
            v-model="form.confirmPwd"
            type="password"
            show-password
            placeholder="请再次输入密码"
          />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱地址" />
        </el-form-item>

        <!-- 协议 -->
        <el-form-item prop="agree">
          <el-checkbox v-model="form.agree">
            我已阅读并同意
            <el-link type="primary" :underline="false">《用户协议》</el-link>
            和
            <el-link type="primary" :underline="false">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            style="width: 100%"
            :loading="loading"
            @click="submitForm(ruleFormRef)"
          >
            立即注册
          </el-button>
        </el-form-item>

        <div style="text-align: right">
          已有账号？
          <router-link to="/">去登录</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
defineOptions({ name: 'registrationPage' });

import { reactive, ref, } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import api from '../utils/request.js'

const router = useRouter()
const ruleFormRef = ref()
const loading = ref(false)

// 表单数据
const form = reactive({
  username: '',
  password: '',
  confirmPwd: '',
  email: '',
  agree: false
})

// 自定义校验：两次密码一致
const validateConfirmPwd = (_, value, callback) => {
  if (value !== form.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 自定义校验：必须勾选协议
const validateAgree = (_, value, callback) => {
  if (!value) {
    callback(new Error('请先阅读并同意相关协议'))
  } else {
    callback()
  }
}

// 校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^\w{3,16}$/, message: '格式错误：3-16位字母/数字/下划线', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 20, message: '长度8-20位', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,20}$/, message: '需包含字母和数字', trigger: 'blur' }  ],
  confirmPwd: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPwd, trigger: 'blur' }
  ],
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
    ],
  agree: [{ validator: validateAgree, trigger: 'change' }]
}



// 提交注册
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (!valid) return
    loading.value = true
    // 调用注册接口
    api.post('/api/auth/register', {
      username: form.username,
      password: form.password,
      confirmPassword: form.confirmPwd,
      email: form.email
    })
    .then((response) => {
      const res = response.data
      if (res.success) {
        ElMessage.success(res.message || '注册成功！')
        router.push('/login')
      } else {
        ElMessage.error(res.message || '注册失败')
      }
    })
    .catch((error) => {
      ElMessage.error(error.response?.data?.message || '注册失败')
    })
    .finally(() => {
      loading.value = false
    })
  })
}
</script>

<style scoped>
.register-container {
  height: 100vh;
  background-image: url('@/assets/picture/background2.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
}
.register-card {

  width: 820px;
  padding: 0 20px 10px;
  height: 500px;
  background-color: rgba(255, 255, 255, 0.7); /* 半透明白色 */
  /* backdrop-filter: blur(1px); 毛玻璃效果，可选 */
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
}
.card-header {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}
.code-row {
  display: flex;
  gap: 12px;
}
</style>
